package com.maxlen.admin.security;

import com.maxlen.admin.entity.Permission;
import com.maxlen.admin.service.IPermissionService;
import com.maxlen.admin.service.IRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import java.util.Collection;
import java.util.List;

/**
 * 根据用户请求的地址，查出这个地址在数据库相应的角色名
 * getAttributes 返回的值会传入到 CustomAccessDecisionManager 的 decide() 方法中
 */
@Component
public class CustomFilterInvocationSecurityMetadataSource implements FilterInvocationSecurityMetadataSource {

    @Autowired
    private IPermissionService permissionService;

    @Autowired
    private IRoleService roleService;

    AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override
    public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {
        String requestUrl = ((FilterInvocation) object).getRequestUrl();
        if(antPathMatcher.match("/admin/permission/router*", requestUrl)){
            return null;
        }
        List<Permission> permissionList = permissionService.list();
        for (Permission permission : permissionList) {
            if(antPathMatcher.match(permission.getPath(), requestUrl)){
                // LogUtils.log(CustomFilterInvocationSecurityMetadataSource.class, requestUrl);
                List<String> roleNameList = roleService.findRoleNameByPermissionId(permission.getId());
                String[] str = new String[roleNameList.size()];
                for (int i = 0; i < roleNameList.size(); i++){
                    str[i] = roleNameList.get(i);
                }
                return SecurityConfig.createList(str);
            }
        }
        return null;
    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return null;
    }

    @Override
    public boolean supports(Class<?> clazz) {
        return true;
    }
}
